<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<style>
    /*这里简单写下用户名和发送内容的样式*/
    .user {
        color: #00a1f4;
        cursor: pointer;
    }

    .content {
        display: inline-block;
        padding: 6px 10px;
        background-color: #00a1f4;
        border-radius: 8px;
        color: #fff;
    }
</style>

<div class="container" style="margin-top: 30px;">
    <div class="row">
        <div class="col-xs-12">
            <div class="panel panel-info">
                <div class="panel-heading">
                    <h4 class="text-center">聊天界面</h4>
                </div>
                <div class="panel-body">
                    <ul id="list" class="list-group" style="height: 300px;overflow: auto;"></ul>
                </div>
                <div class="panel-footer">
                    <div class="row">
                        <div class="col-xs-10">
                            <input type="text" class="form-control" id="input">
                        </div>
                        <div class="col-xs-1">
                            <button class="btn btn-info" id="sendBtn">发送</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<script src="socket.io.js"></script>
<script>
    let socket = io.connect();
    let list = document.getElementById('list'),
            input = document.getElementById('input'),
            sendBtn = document.getElementById('sendBtn');

    // 发送消息的方法
    function send() {
        let value = input.value;
        if (value) {
// 发送消息给服务器
            let data = {
                user: "郭富城",
                id: 1,
                msg: input.value,
                createAt: new Date().toLocaleString()
            };
            socket.emit('sendMsg', data);
            input.value = '';
        } else {
            alert('输入的内容不能为空！');
        }
    }

    // 点击按钮发送消息
    sendBtn.onclick = send;

    // 键盘回车发消息
    function enterSend(e) {
        if (e.keyCode == 13) send()
    }

    input.onkeydown = function (event) {
        enterSend(event)
    }

    // 监听事件，用来接收其他客户端推送的消息
    socket.on("message", function (data) {
        let li = document.createElement('li');
        li.className = 'list-group-item';
        li.innerHTML = `<p style="color: #ccc;"><span class="user" style="color:${data.color}">${data.user} </span>${data.createAt}</p>
<p class="content" style="background-color: ${data.color}">${data.msg}</p>`;
        list.appendChild(li);
// 将聊天区域的滚动条设置到最新内容的位置
        list.scrollTop = list.scrollHeight;
    });
</script>